<template>
  <div class="loginContant" ref="loginContant">
    <div class="loginForm" v-show="!visible">
      <h3>文本撰写助手</h3>
      <h4>HI,感谢再次登录文本撰写助手</h4>
      <a-form
        id="components-form-demo-normal-login"
        :form="form"
        class="login-form"
        @submit="handleSubmit"
      >
        <a-form-item>
          <a-input
            v-decorator="[
              'userName',
              { rules: [{ required: true, message: '用户名不正确!'}] }
            ]"
            placeholder="用户名"
          >
            <a-icon slot="prefix" type="user" style="color: rgba(0,0,0,.25)" />
          </a-input>
        </a-form-item>
        <a-form-item>
          <a-input
            v-decorator="[
              'password',
              { rules: [{ required: true, message: '密码不能低于6位!', min: 6 }] }
            ]"
            type="password"
            placeholder="密码"
          >
            <a-icon slot="prefix" type="lock" style="color: rgba(0,0,0,.25)" />
          </a-input>
        </a-form-item>
        <a-form-item>
          <a-checkbox
            v-decorator="[
              'remember',
              {
                valuePropName: 'checked',
                initialValue: true
              }
            ]"
          >
            <a class="checkPassword">记住密码</a>
          </a-checkbox>
          <a class="login-form-forgot" @click="forgetPassword">忘记密码？</a>
          <a-button
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            style="fontSize: 18px"
          >登录</a-button>
        </a-form-item>
      </a-form>
    </div>
    <!-- 标签设置 -->
    <div class="tags-setting" v-show="visible">
      <div class="tags-header">
        <a-icon type="pushpin" theme="filled" style="color: #fff" />
        <span style="marginLeft: 10px">标签设置</span>
      </div>
      <div class="tags-content">
        <div v-for="(tagRow, index) in tagRows" :key="index" class="tagRowDiv">
          <template v-for="tag in tagRow">
            <a-checkable-tag
              :key="tag"
              :checked="selectedTags.indexOf(tag) > -1"
              @change="checked => handleChange(tag, checked)"
            >{{ tag }}</a-checkable-tag>
          </template>
        </div>
      </div>
      <div class="tags-footer">
        <span class="tag-tips" v-show="selectedTags.length > 0 ? false : true">请选择至少一个感兴趣的标签</span>
        <a-button type="primary" class="tag-button" @click="login">进入系统</a-button>
      </div>
    </div>
    <!-- 忘记密码 -->
    <forgetPassword ref="forgetPassword" />
  </div>
</template>

<script>
import { login, getuserLabelList, saveLabel } from "@/api/login";
import throttle from "lodash.throttle"; //节流
import { mapMutations } from "vuex";
import forgetPassword from "components/login/forgetPassword";
export default {
  data() {
    return {
      loading: false,
      visible: false,
      confirmLoadingLoading: false,
      userName: "",
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
      },
      tailFormItemLayout: {
        wrapperCol: {
          xs: {
            span: 24,
            offset: 0,
          },
          sm: {
            span: 16,
            offset: 8,
          },
        },
      },
      //标签设置数据开始
      tags: [],
      tagRows: [],
      selectedTags: [],
      //标签设置数据结束
    };
  },
  components: {
    forgetPassword,
  },
  beforeCreate() {
    this.form = this.$form.createForm(this, { name: "normal_login" });
    this.findform = this.$form.createForm(this, { name: "findpassword" });
  },
  mounted() {
    this.getCookie();
    window.addEventListener("resize", this.observe);
    this.observe();
    this.$once("hook:beforeDestroy", () => {
      window.removeEventListener("resize", this.observe);
    });
  },
  methods: {
    observe: throttle(function () {
      const dom = this.$refs.loginContant;
      const width = Math.max(dom.scrollWidth, 1200);
      dom.style.height = `${(920 / 1920) * width}px`;
    }, 100),
    //忘记密码
    forgetPassword() {
      this.$refs.forgetPassword.openForgetModal();
    },
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          var res = {
            code: 200,
            msg: "登录成功！",
            data: {
              token:
                "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb290SWQiOiI3NzBlYTRmYzNkMzczZDU5NzNhNjFkNWM2ZTE4YzY5ZCIsImxvZ2luTmFtZSI6ImhlcSIsImlzcyI6Imlzc3VlciIsImRlZmF1bHRVbml0SWQiOiIwIiwiZXhwIjoxNTk4NjMzNDk2LCJ0eXBlIjoiMCIsImlhdCI6MTU5NzkxMzQ5NiwidXNlcklkIjoiNDgzZmI3YjVjNmJlZTIzMjY0M2EzOWE3YzAyYTExNDYifQ.lqcOOx1zuF67KyWhO9_3fXWMo8pqsQZm1dqM4fBPvkg",
              refreshToken: "4181b332b16e4888aa2b8852e65133d9",
              permission: null,
              userId: "483fb7b5c6bee232643a39a7c02a1146",
              loginName: "heq",
              cname: "heq",
              defaultUnitId: "0",
              rootId: "770ea4fc3d373d5973a61d5c6e18c69d",
              unitName: null,
              type: 0,
              photo:
                "http://192.168.4.119:9010/ubom/upload/avatar-vc-upload-1597891658304-2",
              first: false,
            },
          };

          localStorage.setItem("TOKEN", res.data.token);
          localStorage.setItem("refreshToken", res.data.refreshToken);
          localStorage.setItem("userInfo", JSON.stringify(res.data));
          localStorage.setItem("photo", res.data.photo);
          this.$store.commit("SET_USERINFO", res.data);
          if (values.remember) {
            // 调用setCookie()方法保存cookie
            this.setCookie(values.userName, values.password, 7);
          } else {
            // 调用clearCookie()方法清空cookie
            this.clearCookie();
          }
          if (res.data.first) {
            this.visible = true;
            //初始化标签列表
            this.initTagRows();
          } else {
            this.$router.push("/console/configuration/hotMessage/index");
          }
          // login({ loginName: values.userName, password: values.password })
          //   .then((res) => {
          //     if (res.data.code === 200) {
          //       localStorage.setItem("TOKEN", res.data.data.token);
          //       localStorage.setItem(
          //         "refreshToken",
          //         res.data.data.refreshToken
          //       );
          //       localStorage.setItem("userInfo", JSON.stringify(res.data.data));
          //       localStorage.setItem("photo", res.data.data.photo);
          //       this.$store.commit("SET_USERINFO", res.data.data);
          //       if (values.remember) {
          //         // 调用setCookie()方法保存cookie
          //         this.setCookie(values.userName, values.password, 7);
          //       } else {
          //         // 调用clearCookie()方法清空cookie
          //         this.clearCookie();
          //       }
          //       if (res.data.data.first) {
          //         this.visible = true;
          //         //初始化标签列表
          //         this.initTagRows();
          //       } else {
          //         this.$router.push("/console/configuration/hotMessage/index");
          //       }
          //     } else {
          //       this.$message.destroy();
          //       this.$message.error(res.data.msg);
          //     }
          //   })
          //   .catch((err) => {
          //     this.$message.destroy();
          //     this.$message.error(err);
          //   })
          //   .finally(() => {
          //     this.loading = false;
          //   });
        }
      });
    },
    //获取标签列表
    initTagRows() {
      getuserLabelList()
        .then((res) => {
          this.tags = [];
          res.data.forEach((item, index) => {
            this.tags.push(item.label);
          });
          let index = 0;
          while (index < this.tags.length) {
            let colum = Math.random() > 0.5 ? 3 : 4;
            this.tagRows.push(
              this.tags.slice(index, Math.min(index + colum, this.tags.length))
            );
            index += colum;
          }
        })
        .catch((err) => {
          this.$message.destroy();
          this.$message.error(err);
        })
        .finally(() => {});
    },
    //点击标签change
    handleChange(tag, checked) {
      const { selectedTags } = this;
      const nextSelectedTags = checked
        ? [...selectedTags, tag]
        : selectedTags.filter((t) => t !== tag);

      this.selectedTags = nextSelectedTags;
    },
    //点击进入系统
    login() {
      if (this.selectedTags.length > 0) {
        var params = [];
        this.selectedTags.forEach((item, index) => {
          var obj = {
            label: item,
            sort: index,
            type: 1,
          };
          params.push(obj);
        });
        saveLabel(params)
          .then((res) => {
            this.$router.push("/console/configuration/networkHotspot/index");
          })
          .catch((err) => {
            this.$message.destroy();
            this.$message.error(err);
          })
          .finally(() => {});
      }
    },
    // 设置cookie
    setCookie(userName, password, exdays) {
      var date = new Date();
      date.setTime(date.getTime() + 24 * 60 * 60 * 1000 * exdays); // 这里是设置的是3天
      // 拼接cookie
      window.document.cookie =
        "userName" + "=" + userName + ";path=/;expires=" + date.toGMTString();
      window.document.cookie =
        "password" + "=" + password + ";path=/;expires=" + date.toGMTString();
    },
    // 读取cookie
    getCookie() {
      if (document.cookie.length > 0) {
        // 通过分号(;)作为分割符cookie字符串
        var arr = document.cookie.split(";");
        // 循环遍历分隔后字符串数组
        for (var i = 0; i < arr.length; i++) {
          // 再将字符串通过等号(=)进行分割
          var arr2 = arr[i].split("=");
          // 判断查找相对应的值,replace(/\s*/g, "")表示去掉字符串中的空格
          if (arr2[0].replace(/\s*/g, "") === "userName") {
            this.form.setFieldsValue({ userName: arr2[1] });
          } else if (arr2[0].replace(/\s*/g, "") === "password") {
            this.form.setFieldsValue({ password: arr2[1] });
          }
        }
      }
    },
    // 清除cookie
    clearCookie: function () {
      this.setCookie("", "", -1); // 将值置为空，天数为负即可
    },
    ...mapMutations({
      setUserInfo: "SET_USERINFO",
    }),
  },
};
</script>
<style lang="stylus" rel="stylesheet/stylus">
@import '~stylus/mixin.styl';

.loginContant {
  background: url('../../assets/images/bg.png');
  height: 100%;
  width: 100%;
  background-size: 100% 100%;
  overflow: hidden;
  min-width: 1200px;

  .loginForm {
    width: 400px;
    height: 500px;
    position: absolute;
    top: 18%;
    right: 16%;

    h3 {
      height: 38px;
      line-height: 38px;
      font-size: 28px;
      font-weight: 700;
      margin-bottom: 0;
      color: #fff;
    }

    h4 {
      height: 20px;
      line-height: 20px;
      font-size: 16px;
      color: #777;
      margin-top: 10px;
      margin-bottom: 60px;
    }

    .ant-input {
      height: 50px !important;
    }

    .ant-btn {
      height: 50px;
      border: none;
      margin-top: 20px;
      width: 100%;
    }

    .login-form-forgot {
      float: right;
      color: #ffffff;
    }

    .checkPassword {
      color: #ffffff;
    }
  }

  .tags-setting {
    width: 600px;
    height: 614px;
    position: absolute;
    top: 50%;
    right: 5%;
    background-color: rgba(5, 25, 84, 0.6);
    border-radius: 5px;
    margin-top: -307px;
    font-family: 'Microsoft YaHei';

    .tags-header {
      height: 38px;
      line-height: 38px;
      font-size: 16px;
      color: #fff;
      padding: 30px 25px;
    }

    .tags-content {
      width: 600px;
      height: 460px;
      display: -webkit-flex;
      display: -moz-flex;
      display: -ms-flex;
      display: -o-flex;
      display: flex;
      flex-flow: row wrap;
      justify-content: center;
      align-content: center;
      align-items: center;

      .tagRowDiv {
        width: 600px;
        text-align: center;
      }

      .ant-tag-checkable {
        min-width: 106px;
        border-radius: 20px;
        font-size: 16px;
        padding: 8px;
        background-color: #133A75;
        text-align: center;
        color: #fff;
        user-select: none;
        cursor: pointer;
        margin-bottom: 12px;
      }

      .ant-tag-checkable-checked {
        background-color: #099DFF;
      }
    }

    .tags-footer {
      text-align: center;
      line-height: 38px;
      padding-right: 28px;
      margin-top: 16px;

      .tag-tips {
        margin-left: 106px;
        font-size: 14px;
        color: #fff;
        text-align: center;
      }
    }

    .ant-btn-primary {
      width: 106px;
      height: 38px;
      border: 0px;
      border-radius: 5px;
      margin-top: 3px;
      float: right;
      background: linear-gradient(100deg, #167BFB, #3BCFF6);
      box-shadow: 0px 6px 16px rgba(89, 157, 224, 0.58);
    }
  }
}

.ant-drawer-content {
  .ant-input {
    height: 40px !important;
  }

  .ant-btn {
    height: 40px;
  }
}
</style>

<style></style>
